package org.czl.leetcode2;

import java.util.HashMap;

public class l2461 {
    public long maximumSubarraySum(int[] nums, int k) {
        int n = nums.length;
        HashMap<Integer, Integer> map = new HashMap<>();
        long ans = 0;
        long sum = 0;
        int len = 0; //有多少个不同的元素
        for (int i = 0; i < n; i++) {
            int cur = nums[i];
            sum += cur;
            if (!map.containsKey(cur)) {
                map.put(cur, 1);
                len++;
            } else {
                map.put(cur, map.get(cur) + 1);
            }
            if (i < k - 1) {
                continue;
            }
            if (map.size() == k) {
                ans = Math.max(ans, sum);
            }
            int ret = nums[i - k + 1];
            int tem = map.get(ret);
            map.put(ret, tem - 1);
            sum -= ret;
            if (tem == 1) {
                map.remove(ret);
            }
        }
        return ans;
    }
}
